#!/usr/bin/env python3
"""
Bridge program between optimization tool and Java server.
Called by the optimization tool with a parameter file path,
connects to Java server, and returns the result.
"""

import sys
import socket

SERVER_HOST = 'localhost'
SERVER_PORT = 9876

def communicate_with_server(param_file_path):
    """
    Connect to Java server, send parameter file path, receive result.
    """
    try:
        # Create socket and connect to server
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
            sock.connect((SERVER_HOST, SERVER_PORT))
            
            # Send parameter file path
            sock.sendall((param_file_path + '\n').encode('utf-8'))
            
            # Receive result
            result = sock.recv(1024).decode('utf-8').strip()
            
            return result
            
    except ConnectionRefusedError:
        print("ERROR: Cannot connect to Java server. Make sure it's running.", file=sys.stderr)
        sys.exit(1)
    except Exception as e:
        print(f"ERROR: {e}", file=sys.stderr)
        sys.exit(1)

def main():
    if len(sys.argv) != 2:
        print("Usage: bridge.py <parameter_file_path>", file=sys.stderr)
        sys.exit(1)
    
    param_file_path = sys.argv[1]
    
    # Get result from server
    result = communicate_with_server(param_file_path)
    
    # Write result to stdout (as required by optimization tool)
    print(result)

if __name__ == '__main__':
    main()
